package com.dlry.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dlry.entity.DlLeave;
import com.dlry.entity.DlLoginuser;
import com.dlry.serviceImpl.LeaveService;
import com.dlry.serviceImpl.UserService;
import com.dlry.web.valid.LeaveForm;

@Controller
@RequestMapping("/{roler}")
public class LeaveController extends BaseController {
	@Autowired
	private UserService userService;
	@Autowired
	private LeaveService leaveService;

	@RequestMapping(value = "/newleave")
	public String addLeave(Model model) {
		model.addAttribute("leaveForm", new LeaveForm());
		return "newleave";
	}

	@RequestMapping(value = "/saveleave")
	public String saveLeave(@Valid LeaveForm leaveForm, BindingResult result, HttpServletResponse response)
			throws ParseException, IOException {

		if (result.hasErrors()) {
			return "newleave";
		}
		DlLeave leave = leaveForm.toDlLeave();
		DlLoginuser user = userService.findByName(getPrincipal());
		leave.setUser(user);
		Timestamp nowstamp = new Timestamp(new Date().getTime());
		leave.setCreatedDate(nowstamp);
		leave.setName(user.getRealName());
		leaveService.save(leave);
		response.reset();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		PrintWriter writer = response.getWriter();
		writer.println("提交成功，请关闭本页。");
		return null;
	}

	@RequestMapping(value = "/deleteleave")
	public String deleteLeave(Long lId, @PathVariable("roler") String roler) {
		leaveService.delete(lId);
		return "redirect:/" + roler + "/leave";
	}
}
